-module(test_chord).
-compile(export_all).

%% Example usage!!!!!
%%
%% In the master:
%% 
%% set_func(fun test_chord:suite1/1,10,"test_chord.beam").
%%
%% run_tests([nodes],100).
%%

%% Tets put and get in peter's chord
%% Params = [[database nodes],Amount of queries in each run]
suite1(Params) ->
   DB_Nodes = lists:nth(1,Params),
   Amount   = lists:nth(2,Params),
 
   %% Pick a node to communicate with 
   {Place,_} = random:uniform_s(length(DB_Nodes),now()), 
   {_,Node} = lists:nth(Place,DB_Nodes),

   %% Create random content
   C = [ {random_string(10,"abcdepcb"),
          random_string(10,"kokokp") }
       || _ <- lists:seq(1,Amount+1) ],

   D = lists:nthtail(1,C),
   
   io:fwrite(to_string(D)),

   %% Put the random content
   do_puts(D,Node),

   %% Get the random content
   QueryResults = [ element(2,do_get(K,Node)) || {K,_} <- D ],
   
   to_string(QueryResults),

   %% Compare put and get and return equals
   D == QueryResults.

do_puts([],_) -> ok;
do_puts([K|Ks],Node) ->
   {Key,Val} = K,
   gen_server:call({store,Node}, {put,Key,Val}),
   do_puts(Ks,Node).

do_get(Key,Node) ->
   gen_server:call({store,Node},{get,Key}).

random_string(Length,AllowedChars) ->
   random_string_help(Length,AllowedChars,now()).

random_string_help(0,_,_) -> [];
random_string_help(Length,AllowedChars,Seed) ->
   {NewInt,NewSeed} = random:uniform_s(length(AllowedChars),Seed),
   [lists:nth(NewInt,AllowedChars)] ++ 
            random_string_help(Length-1,AllowedChars,NewSeed).
   
% A toString function for writing Ints
to_string(Something) ->
   case length(Something) of
      1 -> io_lib:format("~p", Something);
      _ -> lists:flatten(io_lib:format("~p", [Something]))
   end.
